package com.zzh.mvvm.binding.click.observable;


import android.view.View;

import com.zzh.mvvm.binding.internal.Preconditions;
import com.zzh.rxandroid.MainThreadDisposable;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;

/**
 * Created by zzh on 2023/11/1.
 *
 * @date: 2023/11/1 20:47
 * @email: zzh_hz@126.com
 * @author: zzh
 * @description: com.zzh.mvvm.binding.click.observable
 */
public class ViewLongClickObservable extends Observable<Object> {
    private View view;
    OnHandledCallback mCallback;

    public ViewLongClickObservable(View view, OnHandledCallback callback) {
        this.view = view;
        mCallback = callback;
    }

    @Override
    protected void subscribeActual(@NonNull Observer<? super Object> observer) {
        if (!Preconditions.checkMainThread(observer)) {
            return;
        }
        Listener listener = new Listener(view, mCallback, observer);
        observer.onSubscribe(listener);
        view.setOnLongClickListener(listener);
    }

    private class Listener extends MainThreadDisposable implements View.OnLongClickListener {

        private View view;
        private Observer<Object> observer;
        OnHandledCallback callback;

        public Listener(View view, OnHandledCallback callback, Observer<Object> observable) {
            this.view = view;
            this.observer = observable;
            this.callback = callback;
        }

        @Override
        protected void onDispose() {
            view.setOnClickListener(null);
        }

        @Override
        public boolean onLongClick(View v) {
            if (!isDisposed()) {
                try {
                    if (callback.handled()) {
                        observer.onNext(v);
                        return true;
                    }
                } catch (Exception e) {
                    observer.onError(e);
                    dispose();
                }

            }

            return false;
        }
    }

    public interface OnHandledCallback {
        boolean handled();
    }
}
